package baiqi.sishen.community.service;

import baiqi.sishen.community.mapper.UserMapper;
import baiqi.sishen.community.model.User;
import baiqi.sishen.community.model.UserExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 兕神
 * @version 1.0
 * DateTime: 2023/4/27
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 用于用户的插入或更新
     * @param user 用户
     */
    public void insertOrUpdate(User user) {

        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andAccountIdEqualTo(user.getAccountId());
        List<User> users = userMapper.selectByExample(userExample);
        //判断用户是否为空
        if (users.size()==0) {
            //无该用户，插入该用户
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            userMapper.insert(user);
        }else {
            //有该用户，更新信息
            User dbUser = users.get(0);
            //更新修改时间
            user.setGmtModified(System.currentTimeMillis());
            UserExample example = new UserExample();
            example.createCriteria()
                    .andIdEqualTo(dbUser.getId());
            userMapper.updateByExampleSelective(user, example);
        }
    }
}
